package com.zzptc.myk.shop.dao;

import com.zzptc.myk.shop.db.DBI;
import com.zzptc.myk.shop.db.DBImpl;
import com.zzptc.myk.shop.vo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDaoI{
    @Override
    public List<User> getAlluser() throws SQLException {
        return null;
    }

    @Override
    public int insert(User user) throws SQLException {
        DBI db = new DBImpl();
        int flag = 0;
        Connection connection = db.getConn();
        String sql = "insert into taotaobuy_user(tu_id,tu_name,tu_password) values(?,?,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setObject(1,user.getuId());
        ps.setObject(2,user.getuId());
        ps.setObject(3,user.getuPassWord());
        flag = ps.executeUpdate();
        ps.close();
        db.closeConn();
        return flag;
    }

    @Override
    public int update(User user) throws SQLException {
        return 0;
    }

    @Override
    public User getUser(String uname, String upass) throws SQLException {
        //1、打开数据库连接
        DBI db = new DBImpl();
        Connection con = db.getConn();
        String sql = "SELECT * FROM taotaobuy_user where tu_id=? and tu_password=?";
        //2、发送sql语句
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setObject(1,uname);
        ps.setObject(2,upass);
        //3、将数据库中数据放入虚拟表ResultSet中
        ResultSet rs = ps.executeQuery();
        List<User> list = new ArrayList<User>();
        //4、将虚拟表中的数据放入集合list中
        while (rs.next()) {
            User user = new User();
            user.setuId(rs.getString(1));
            user.setuName(rs.getString(2));
            user.setuPassWord(rs.getString(3));
            user.setuSex(rs.getString(4));
            user.setuBirthday(rs.getDate(5));
            user.setuIdentityCode(rs.getString(6));
            user.setuEmail(rs.getString(7));
            user.setuMobile(rs.getString(8));
            user.setuAddress(rs.getString(9));
            user.setuStatus(rs.getInt(10));

            list.add(user);
        }
        //4、释放资源
        db.closeAll(null,ps,rs);
        //5、关闭数据库
        db.closeConn();
        return list!=null&&list.size()>0?list.get(0):null;
    }
}
